package com.itheima.admin.controller;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.itheima.admin.pojo.AdUser;
import com.itheima.admin.service.AdUserService;
import com.itheima.common.pojo.Result;
import com.itheima.common.util.Md5Util;
import com.itheima.common.util.RandomUtil;
import com.itheima.core.controller.AbstractCoreController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* <p>
* 管理员用户信息表 控制器</p>
* @author 作者
* @since 2021-08-19
*/
@RestController
@RequestMapping("/account")
public class LoginController extends AbstractCoreController<AdUser> {

    private AdUserService adUserService;

    //注入
    @Autowired
    public LoginController(AdUserService adUserService) {
        super(adUserService);
        this.adUserService=adUserService;
    }

    /***
     * 注册
     */
    @PostMapping(value = "/register")
    public Result register(@RequestBody AdUser adUser){
        //1:获取密码[明文]
        //2:随机生成盐
        String random = RandomUtil.random(20);
        //3:密码加密（加盐、加密）
        String pwd = Md5Util.toMD5(adUser.getPassword(), random);

        //4:保存数据
        adUser.setPassword(pwd);
        adUser.setSalt(random);
        adUserService.save(adUser);
        return Result.ok();
    }


    /**
     * 登录
     *  1:name+password
     *  2:匹配密码：根据name查询AdUser
     *  3:获取AdUser.salt
     *  4:MD5(password+AdUser.salt)==AdUser.password?
     *  5:匹配成功，登录成功-颁发令牌
     *    匹配失败，登录失败
     */
    @PostMapping(value = "/login")
    public Result login(@RequestBody AdUser adUser){
        String token = adUserService.login(adUser);
        if(!StringUtils.isEmpty(token)){
            //登录成功
            return Result.ok(token);
        }
        return Result.errorMessage("账号或者密码错误！");
    }

}

